package exam.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import exam.common.Result;
import exam.file.domain.UFile;
import exam.file.service.UFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;


/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/10 3:00
 * @since JDK 1.8
 */
@RestController
@RequestMapping("file")
@Api(tags = {"文件管理服务模块"})
public class UFileController {

    private static String UPLOAD_PATH_PREFIX="upload";

    @Autowired
    private UFileService uFileService;

    @ApiOperation("文件上传服务模块")
    @RequestMapping(value="/uploadFile",method={RequestMethod.POST})
    @ResponseBody
    public JSONObject uploadFileController(HttpServletRequest request, HttpServletResponse response){
        // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
        MultipartFile file= multipartRequest.getFile("file_data");
        if(file==null){
            return Result.errorObject("上传文件不得为空");
        }
        //文件名
        String fileName = file.getOriginalFilename();
        //文件类型
        String type=file.getContentType();
        String realPath = new String(UPLOAD_PATH_PREFIX);
        //文件大小
        Long size1=(file.getSize()/1024)/1024;
        Double size = Double.valueOf(String.valueOf(size1)) ;

        File file1 = new File(realPath );
        if(!file1.isDirectory()){
            file1.mkdirs();
        }
        try {
            File dest = new File(file1.getAbsoluteFile() + File.separator+fileName);
            file.transferTo( dest ); //保存文件
            //文件路径
            String path=dest.getPath();
            UFile uFile=UFile.builder().sizeType("m").size(size)
                    .fileType(type).realFileName(fileName).path(path)
                    .filename(fileName).build();
            Boolean flag=uFileService.save(uFile);
            if(flag){
                return Result.successObject("上传成功");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.errorObject("上传出错");
    }

    @PostMapping("filelist")
    @ApiOperation("文件列表服务模块")
    public JSONObject getFileListController(@ApiParam("页码") @RequestParam("pageNum")Integer pageNum,
                                            @ApiParam("条数")@RequestParam("pageSize")Integer pageSize,
                                            @ApiParam("关键字")@RequestParam(value = "keyword",required = false)String keyword){
        LambdaQueryWrapper<UFile> uFileLambdaQueryWrapper= Wrappers.lambdaQuery();
        if(StringUtils.hasText(keyword)){
            uFileLambdaQueryWrapper.like(UFile::getFilename,keyword);
            uFileLambdaQueryWrapper.like(UFile::getFileType,keyword);
            uFileLambdaQueryWrapper.like(UFile::getPath,keyword);
        }
        uFileLambdaQueryWrapper.orderByDesc(UFile::getCreateTime);
        IPage<UFile> uFileIPage=uFileService.page(new Page(pageNum,pageSize),
                uFileLambdaQueryWrapper);
        return Result.successObject(uFileIPage.getTotal(),
                uFileIPage.getRecords());
    }

    @ApiOperation("文件删除")
    @GetMapping("filedelete")
    public JSONObject deleteFileController(@ApiParam("文件id")@RequestParam("id")String id){
        if(!StringUtils.hasText(id)){
            return Result.errorObject("必要参数不得为空");
        }
        UFile uFile=uFileService.getById(id);
        if(uFile==null){
            return Result.errorObject("文件数据已过期");
        }
        boolean flag=uFileService.removeById(id);
        if(flag){
            return Result.successObject("文件删除成功");
        }
        return Result.errorObject("文件删除失败");
    }
}
